package yana.tpe.shop;

import java.net.MalformedURLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 */
public class App {

    public static void main(String[] args) {
        if (args == null || args.length < 2) {
            System.out.println("Use: <task_number> <string>");
            System.out.println("\tFor example: 1 2012-12-01");
            return;
        }

        try {
            switch (Integer.parseInt(args[0])) {
                case 1:
                    new App().task1(args[1]);
                    break;
                case 2:
                    new App().task2(args[1]);
                    break;
                case 3:
                    new App().task3(args[1]);
                    break;
                default:
                    System.out.println("supported number of tasks is: 1, 2, 3.");
            }
        } catch (RuntimeException ex) {
            throw ex;
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    public void task1(String date) throws ParseException {
//        // correct:
//        java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-mm-dd");
//        df.parse(date);

        // incorrect
        Pattern pattern = Pattern.compile("\\d\\d\\d\\d\\-(1(0|1|2)|0[1-9])\\-((0|1|2)\\d|3(0|1))");
        Matcher matcher = pattern.matcher(date);
        if (!matcher.matches()) {
            throw new IllegalArgumentException("Unmatched string " + date);
        }
    }

    public void task2(String urlString) throws MalformedURLException {
//        // correct:
//        java.net.URL url = new java.net.URL(urlString);

        // incorrect
        Pattern pattern = Pattern.compile(
                "((\\w){2,4}\\:\\/)?" // protocol
                + "(\\/\\w+)(\\.\\w+)*" // host
                + "(\\/\\w+)*" // path
                + "(\\/\\?\\w+(\\=\\w+)?(\\&\\w+(\\=\\w+)?)*)?" // props
                + "(\\/)?");
        Matcher matcher = pattern.matcher(urlString);
        if (!matcher.matches()) {
            throw new IllegalArgumentException("Unmatched string " + urlString);
        }
    }

    public List<String> task3(String email) {
        List<String> list = new ArrayList<String>();
        Pattern pattern = Pattern.compile(
                "[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*\\@"
                + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})");
        Matcher matcher = pattern.matcher(email);
        while (matcher.find()) {
            list.add(email.substring(matcher.start(), matcher.end()));
        }
        return list;
    }
}
